﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace Coco.Converters
{
    public class ValueInRangeToBooleanConverter : IValueConverter
    {
        public ValueInRangeToBooleanConverter()
        {
            this.LowerBound = 0;
            this.UpperBound = int.MaxValue;
        }

        public double LowerBound { get; set; }
        public double UpperBound { get; set; }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return false;

            if (value is double)
            {
                var castedValue = (double)value;
                return castedValue >= this.LowerBound && castedValue <= this.UpperBound;
            }

            if (value is double?)
            {
                var castedValue = (double?)value;
                return castedValue >= this.LowerBound && castedValue <= this.UpperBound;
            }

            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var boolValue = value as bool?;
            if (boolValue.HasValue && boolValue.Value)
                return this.LowerBound;

            return this.LowerBound != int.MinValue
                ? this.LowerBound - 1
                : this.UpperBound + 1; // just return something outside of range.
        }
    }
}
